﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.Providers
{
    [Serializable]
    public class SamplingInstruction:InstructionBase
    {
        #region props
        private string _EntityProviderFilePath;
        /// <summary></summary>
        public string EntityProviderFilePath
        {
            get
            {
                return this._EntityProviderFilePath;
            }
            set
            {
                this._EntityProviderFilePath = value;
            }
        }

        private DataProviderType _DbProvider;
        /// <summary></summary>
        public DataProviderType DbProvider
        {
            get
            {
                return this._DbProvider;
            }
            set
            {
                this._DbProvider = value;
            }
        }

        private string _ConnStr;
        /// <summary></summary>
        public string ConnStr
        {
            get
            {
                return this._ConnStr;
            }
            set
            {
                this._ConnStr = value;
            }
        }

        private string _SelectSql;
        /// <summary></summary>
        public string SelectSql
        {
            get
            {
                return this._SelectSql;
            }
            set
            {
                this._SelectSql = value;
            }
        }

        private string _IDAttributeName;
        /// <summary></summary>
        public string IDAttributeName
        {
            get
            {
                return this._IDAttributeName;
            }
            set
            {
                this._IDAttributeName = value;
            }
        }

        private string _SeedAttributeName;
        /// <summary>
        /// when seed attribute is available, it sample soruce data using seed value
        /// randomly select a seed value from sorted seed values
        /// </summary>
        public string SeedAttributeName
        {
            get
            {
                return this._SeedAttributeName;
            }
            set
            {
                this._SeedAttributeName = value;
            }
        }

        private SamplingMethod _Method;
        /// <summary></summary>
        public SamplingMethod Method
        {
            get
            {
                return this._Method;
            }
            set
            {
                this._Method = value;
            }
        }

        private int _SampleSize;
        /// <summary></summary>
        public int SampleSize
        {
            get
            {
                return this._SampleSize;
            }
            set
            {
                this._SampleSize = value;
            }
        }

        private Dictionary<string,string> _Filters;
        /// <summary></summary>
        public Dictionary<string, string> Filters
        {
            get
            {
                return this._Filters;
            }
            set
            {
                this._Filters = value;
            }
        }

        private Dictionary<string,Range<int>> _RangeFilters;
        /// <summary></summary>
        public Dictionary<string,Range<int>> RangeFilters
        {
            get
            {
                return this._RangeFilters;
            }
            set
            {
                this._RangeFilters = value;
            }
        }

        private string _SamplingResultFilePath;
        /// <summary></summary>
        public string SamplingResultFilePath
        {
            get
            {
                return this._SamplingResultFilePath;
            }
            set
            {
                this._SamplingResultFilePath = value;
            }
        }
        #endregion

        #region ctor
        public SamplingInstruction():base(Guid.Empty,Guid.Empty)
        {
            this._EntityProviderFilePath = string.Empty;
            this._DbProvider = DataProviderType.MSSQL;
            this._ConnStr = string.Empty;
            this._SelectSql = string.Empty;
            this._IDAttributeName = string.Empty;
            this._SeedAttributeName = string.Empty;
            this._Method = SamplingMethod.Count;
            this._SampleSize = 100;
            this._Filters = new Dictionary<string, string>();
            this._RangeFilters = new Dictionary<string, Range<int>>();
            this._SamplingResultFilePath = string.Empty;
        }

        public SamplingInstruction(Guid componentID, Guid jobTicketID,
            string entityProviderFilePath, 
            DataProviderType dbProvider,
            string connStr, 
            string sql,
            string idAttrName,
            string seedAttrName,
            SamplingMethod method,
            int size,
            Dictionary<string, string> filters,
            Dictionary<string,Range<int>> rangeFilters,
            string resultFilePath) 
            : base(componentID, jobTicketID)
        {
            this._EntityProviderFilePath = entityProviderFilePath;
            this._DbProvider = dbProvider;
            this._ConnStr = connStr;
            this._SelectSql = sql;
            this._IDAttributeName = idAttrName;
            this._SeedAttributeName = seedAttrName;
            this._Method = method;
            this._SampleSize = size;
            this._Filters = filters;
            this._RangeFilters = rangeFilters;
            this._SamplingResultFilePath = resultFilePath;
        }
        #endregion

        public override InstructionBase Instantiate(XmlNode xNode)
        {
            if (xNode.Attributes.GetNamedItem("Type").Value == this.GetType().FullName)
            {
                SamplingInstruction instruction = new SamplingInstruction();
                instruction.OwnerComponentID = new Guid(xNode.Attributes.GetNamedItem("ComponentID").Value);
                instruction.OwnerWorkerInstanceID = new Guid(xNode.Attributes.GetNamedItem("WorkerID").Value);
                instruction.SubmitTime = DateTime.Parse(xNode.Attributes.GetNamedItem("SubmitTime").Value);
                instruction.StartTime = DateTime.Parse(xNode.Attributes.GetNamedItem("StartTime").Value);

                instruction.EntityProviderFilePath = XmlDataUtil.GetAttributeValue(xNode, "EntityProviderFilePath", "");
                instruction.DbProvider = (DataProviderType) int.Parse(
                                                                XmlDataUtil.GetAttributeValue(xNode, "DbProvider",
                                                                                              ((int)
                                                                                               DataProviderType.MSSQL).
                                                                                                  ToString()));
                instruction.ConnStr = XmlDataUtil.GetAttributeValue(xNode, "ConnStr", "");
                instruction.SelectSql = XmlDataUtil.GetAttributeValue(xNode, "SelectSql", "");
                instruction.IDAttributeName = XmlDataUtil.GetAttributeValue(xNode, "IDAttributeName", "");
                instruction.SeedAttributeName = XmlDataUtil.GetAttributeValue(xNode, "SeedAttributeName", "");
                instruction.Method =
                    (SamplingMethod)
                    int.Parse(XmlDataUtil.GetAttributeValue(xNode, "Method", ((int) SamplingMethod.Count).ToString()));
                instruction.SampleSize = int.Parse(XmlDataUtil.GetAttributeValue(xNode, "Size", "100"));
                instruction.SamplingResultFilePath = XmlDataUtil.GetAttributeValue(xNode, "ResultFilePath", "");

                XmlNodeList filterNodes = xNode.SelectNodes("Filters/Filter");
                if(filterNodes !=null && filterNodes.Count>0)
                {
                    instruction.Filters = new Dictionary<string, string>();
                    foreach(XmlNode filterNode in filterNodes)
                    {
                        string attrName = XmlDataUtil.GetAttributeValue(filterNode, "AttributeName", "");
                        string attrValue = XmlDataUtil.GetAttributeValue(filterNode, "AttributeValue", "");
                        instruction.Filters.Add(attrName, attrValue);
                    }
                }

                XmlNodeList rangeFilterNodes = xNode.SelectNodes("RangeFilters/RangeFilter");
                if(rangeFilterNodes !=null && rangeFilterNodes.Count>0)
                {
                    instruction.RangeFilters = new Dictionary<string, Range<int>>();
                    foreach(XmlNode rangeNode in rangeFilterNodes)
                    {
                        string attrName = XmlDataUtil.GetAttributeValue(rangeNode, "AttributeName", "");
                        Range<int> range = new Range<int>();
                        range.FromValue = int.Parse(XmlDataUtil.GetAttributeValue(rangeNode, "From", "0"));
                        range.ToValue = int.Parse(XmlDataUtil.GetAttributeValue(rangeNode, "To", "100"));
                        instruction.RangeFilters.Add(attrName, range);

                    }
                }
                
                return instruction;
            }
            else
            {
                throw new Exception("Unable to instantiate instruction: invalid type specified in xml node");
            }
        }

        public override XmlNode Serialize(ref XmlDocument xDoc, ref XmlNode parentNode)
        {
            XmlNode xNode = XmlDataUtil.AddElement(ref xDoc, parentNode, "Instruction");
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "Type", this.GetType().FullName);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "ComponentID", this.OwnerComponentID.ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "WorkerID", this.OwnerWorkerInstanceID.ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "SubmitTime", this.SubmitTime.ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "StartTime", this.StartTime.ToString());

            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "EntityProviderFilePath", this.EntityProviderFilePath);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "DbProvider", ((int) this.DbProvider).ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "ConnStr", this.ConnStr);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "SelectSql", this.SelectSql);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "IDAttributeName", this.IDAttributeName);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "SeedAttributeName",this.SeedAttributeName);
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "Method", ((int) this.Method).ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "Size", this.SampleSize.ToString());
            XmlDataUtil.UpdateAttribute(ref xDoc, xNode, "ResultFilePath", this.SamplingResultFilePath);

            if(this.Filters !=null && this.Filters.Count>0)
            {
                XmlNode filterRootNode = XmlDataUtil.AddElement(ref xDoc, xNode, "Filters");
                foreach(string attrName in this.Filters.Keys)
                {
                    XmlNode filterNode = XmlDataUtil.AddElement(ref xDoc, filterRootNode, "Filter");
                    XmlDataUtil.UpdateAttribute(ref xDoc, filterNode, "AttributeName", attrName);
                    XmlDataUtil.UpdateAttribute(ref xDoc, filterNode, "AttributeValue", this.Filters[attrName]);
                }
            }

            if(this.RangeFilters !=null && this.RangeFilters.Count>0)
            {
                XmlNode rangeRootNode = XmlDataUtil.AddElement(ref xDoc, xNode, "RangeFilters");
                foreach(string attrName in this.RangeFilters.Keys)
                {
                    XmlNode rangeNode = XmlDataUtil.AddElement(ref xDoc, rangeRootNode, "RangeFilter");
                    XmlDataUtil.UpdateAttribute(ref xDoc, rangeNode, "AttributeName", attrName);
                    XmlDataUtil.UpdateAttribute(ref xDoc, rangeNode, "From",
                                                this.RangeFilters[attrName].FromValue.ToString());
                    XmlDataUtil.UpdateAttribute(ref xDoc, rangeNode, "To",
                                                this.RangeFilters[attrName].ToValue.ToString());
                }
            }
            
            return xNode;
        }
    }
}
